﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using GolSig.Library;

namespace GolSig.WPF
{
   
    public partial class MainWindow : Window, IMainWindow
    {

        private readonly DispatcherTimer _timer;
        private readonly BoardSize _boardSize = new BoardSize(50, 50);
        private readonly MainWindowPresenter _mainWindowPresenter;

        public MainWindow()
        {
            InitializeComponent();
            _mainWindowPresenter = new MainWindowPresenter(this);

            _timer = new DispatcherTimer { IsEnabled = false };
            _timer.Tick += TimerTick;
            _timer.Interval = new TimeSpan(0, 0, 0, 0, 300);


        }

        void TimerTick(object sender, EventArgs e)
        {

            _mainWindowPresenter.NextState();

        }

        private void InitButtonClick(object sender, RoutedEventArgs e)
        {
            _mainWindowPresenter.Initialize();
        }



        private void StepButtonClick(object sender, RoutedEventArgs e)
        {
            _mainWindowPresenter.Step();
        }

        private void AnimateButtonClick(object sender, RoutedEventArgs e)
        {
            _mainWindowPresenter.Animate();
        }


        public BoardSize GetBoardSize()
        {
            return _boardSize;
        }

        public void ShowGridContent(IEnumerable<CellInfo> cells)
        {
            mainGrid.Children.Clear();
            foreach (var cellInfo in cells)
            {
                // based on example in http://odetocode.com/articles/444.aspx
                var rectangle = new Rectangle { Width = 5, Height = 5 };
                Grid.SetColumn(rectangle, cellInfo.Position.Column);
                Grid.SetRow(rectangle, cellInfo.Position.Row);
                rectangle.Fill = cellInfo.Alive ? Brushes.Black : Brushes.White;
                mainGrid.Children.Add(rectangle);
            }
        }

        public void SetupGrid()
        {
            for (int i = 0; i < _boardSize.Rows; i++)
            {
                mainGrid.RowDefinitions.Add(new RowDefinition());
            }

            for (int i = 0; i < _boardSize.Columns; i++)
            {
                mainGrid.ColumnDefinitions.Add(new ColumnDefinition());
            }
        }

        public void StopTimer()
        {
            _timer.IsEnabled = false;
        }

        public void StartTimer()
        {
            _timer.IsEnabled = true;
        }
    }
}
